import 'package:collection/collection.dart';
import 'package:e_reception_flutter/common_widgets/common_stack_page_widget/common_stack_page_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/bean/terminal_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/menu_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:transformer_page_view/transformer_page_view.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

/// 终端详情-轮播横向列表项
///
/// @author: zengxiangxi
/// @createTime: 2/4/21 2:35 PM
/// @specialDemand:
class TerminalDetailPageViewWidget extends StatefulWidget {
  final Axis axis;

  final List<TerminalDetailListItemBean> list;

  final ValueNotifier<String> jumpToFolderIdValueNotifier;

  final ValueChanged<TerminalDetailListItemBean> onTap;

  final ValueChanged<TerminalDetailListItemBean> onRepeat;

  final ValueChanged<TerminalDetailListItemBean> onDeleteTap;

  final ValueChanged<TerminalDetailListItemBean> onDeleteForever;

  final ValueChanged<TerminalDetailListItemBean> onUpdateName;

  final ValueNotifier<List<TerminalDetailListItemBean>> dataUpdateValueNotifier;

  const TerminalDetailPageViewWidget(
      {Key key, @required this.axis, this.list, this.jumpToFolderIdValueNotifier,
        this.dataUpdateValueNotifier,
        this.onRepeat,
        this.onTap, this.onDeleteTap, this.onDeleteForever, this.onUpdateName,})
      : super(key: key);

  @override
  _TerminalDetailPageViewWidgetState createState() =>
      _TerminalDetailPageViewWidgetState();
}

class _TerminalDetailPageViewWidgetState
    extends State<TerminalDetailPageViewWidget> {
  TransformerPageController _pageController;

  double _screenW;

  double _itemWidth;

  double _itemHeight;

  static const double HOR_ITEM_WIDTH = 204;
  static const double HOR_ITEM_HEIGHT = 114.75;

  static const double VER_ITEM_WIDTH = 120;
  static const double VER_ITEM_HEIGHT = 213.3333;

  static const int LIMIT_LOOP_COUNT = 2000;

  List<TerminalDetailListItemBean> urlList;

  ValueNotifier<int> _pageValueNotifier;

  Key _pageViewKey = UniqueKey();
  String _selectId = "";


  @override
  void initState() {
    super.initState();
    _screenW = ScreenUtils.screenW(AppMain.context);
    if (widget.axis == Axis.horizontal) {
      _itemWidth = _screenW * HOR_ITEM_WIDTH / 375;
      _itemHeight = _itemWidth * HOR_ITEM_HEIGHT / HOR_ITEM_WIDTH;
    } else if (widget.axis == Axis.vertical) {
      _itemWidth = _screenW * VER_ITEM_WIDTH / 375;
      _itemHeight = _itemWidth * VER_ITEM_HEIGHT / VER_ITEM_WIDTH;
    } else {
      throw NullThrownError();
    }
    _pageValueNotifier = ValueNotifier(_getInitPositon());
    _pageController = TransformerPageController(
        keepPage: true,
        initialPage: _getInitPositon(),
        loop: false,
        viewportFraction: _itemWidth / _screenW);
    _initListener();



    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {

    });
  }

  _initListener() {
    widget?.jumpToFolderIdValueNotifier?.addListener(() {
      String newFolderId = widget?.jumpToFolderIdValueNotifier?.value;
      if (StringUtils.isEmpty(newFolderId)) {
        return;
      }

      _newFolderIdJump(newFolderId);
    });
    widget?.dataUpdateValueNotifier?.addListener(() {
      List<TerminalDetailListItemBean> data = widget?.dataUpdateValueNotifier?.value;
      if(data != null){
        data.forEach((element) {
            if("01" == element.stopflg??""){
              _selectId = element.id;
            }
          });
      }
    });
  }

  @override
  void didUpdateWidget(TerminalDetailPageViewWidget oldWidget) {
    bool isRefresh = true;
    Function eq = const ListEquality().equals;
    if (eq(urlList, widget?.list)) {
      isRefresh = false;
    } else {
      isRefresh = true;
    }
    urlList = widget?.list;
    if (isRefresh) {
      Future.delayed(Duration(microseconds: 0), () {
        _pageViewKey = UniqueKey();
        if (widget.axis == Axis.horizontal) {
          _itemWidth = _screenW * HOR_ITEM_WIDTH / 375;
          _itemHeight = _itemWidth * HOR_ITEM_HEIGHT / HOR_ITEM_WIDTH;
        } else if (widget.axis == Axis.vertical) {
          _itemWidth = _screenW * VER_ITEM_WIDTH / 375;
          _itemHeight = _itemWidth * VER_ITEM_HEIGHT / VER_ITEM_WIDTH;
        } else {
          throw NullThrownError();
        }

        _pageController = TransformerPageController(
            keepPage: true,
            initialPage: _getInitPositon(),
            loop: false,
            viewportFraction: _itemWidth / _screenW);
        _pageValueNotifier?.value = _getInitPositon();
        setState(() {});
      });
    }

    super.didUpdateWidget(oldWidget);
  }

  ///初始化位置
  int _getInitPositon() {
    int initIndex = 0;
    // if(urlList != null){
      urlList?.forEach((element) {
        if("01" == element.stopflg){
          initIndex = urlList.indexOf(element);
        }
      });
    // }
    return ((urlList?.length ?? 0) * LIMIT_LOOP_COUNT / 2).floor() + initIndex;

  }

  ///根据文件名跳转
  void _newFolderIdJump(String newFolderId) {
    if (StringUtils.isEmpty(newFolderId)) {
      return;
    }
    print("跳转：$newFolderId");
    //检索
    int current;
    int i = 0;
    if (StringUtils.isNotEmpty(newFolderId)) {
      for (TerminalDetailListItemBean item in urlList) {
        if (newFolderId == item?.picid) {
          current = i;
          break;
        }
        i++;
      }
    }
    if (current == null || current < 0) {
      return;
    }
    int position = ((urlList?.length ?? 0) * LIMIT_LOOP_COUNT / 2).floor() +
        current;
    _pageController.jumpToPage(position);
    _pageValueNotifier?.value = position;
  }

  @override
  void dispose() {
    _pageController?.dispose();
    _pageValueNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    urlList = widget?.list;

    return Container(
        padding: const EdgeInsets.only(top: 20, bottom: 15),
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        child: _toMainColumnWidget());
  }

  Column _toMainColumnWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        _toSwiper(),
        SizedBox(height: 12.7),
        _toTitleWidget(),
      ],
    );
  }

  Widget _toTitleWidget() {
    return Container(
      height: 42,
      alignment: Alignment.center,
      child: ValueListenableBuilder(
        valueListenable: _pageValueNotifier,
        builder: (BuildContext context, int index, Widget child) {
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                _selectId = StringUtils.isEmpty(_selectId)?
                urlList?.elementAt(index % (urlList?.length))?.id
                    :"";
                setState(() {
                });
                urlList?.elementAt(index % (urlList?.length))?.editStopFlg = !StringUtils.isEmpty(_selectId)?"01":"02";
                widget?.onRepeat?.call(urlList?.elementAt(index % (urlList?.length)));
              },
              child: Container(
                height: 42,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    AnimatedSwitcher(
                      duration: DEFAULT_ANIM_DURATION,
                      child: Image.asset(
                        !StringUtils.isEmpty(_selectId)
                            ? "images/icon_image_selected.png"
                            : "images/icon_image_unselected.png",
                        width: 18,
                        height: 18,
                      ),
                    ),
                    SizedBox(
                      width: 6,
                    ),
                    Text(
                      "重复播放当前文件",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        // ignore: unrelated_type_equality_checks
                          color: !StringUtils.isEmpty(_selectId)?
                          ThemeRepository.getInstance()
                              .getTextMainColor_D0E0F7()
                          :Color(0xFF5E687C),
                          fontSize: 12,
                          height: 1.2),
                    ),
                  ],
                ),
              ),
            ),
//            child: AnimatedSwitcher(
//              duration: Duration(milliseconds: 200),
//              child: Text(
//                index == null ? "" : _getFolderNameStr(index) ?? "",
//                maxLines: 1,
//                key: ValueKey(index),
//                overflow: TextOverflow.ellipsis,
//                style: TextStyle(
//                  color: ThemeRepository.getInstance()
//                      .getTextMinorGreyColor_808388(),
//                  fontSize: 12,
//                ),
//              ),
//            ),
          );
        },
      ),
    );
  }

  Widget _toSwiper() {
    return Container(
      height: _itemHeight,
      child: _toTransformerPageViewWidget(),
    );
  }

  Widget _toTransformerPageViewWidget() {
    if (urlList == null || urlList.isEmpty) {
      _pageValueNotifier.value = null;
      return Center(
        child: Text(
          "暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
            fontSize: 20,
          ),
        ),
      );
    }
    return ScrollConfiguration(
      behavior: MyBehavior(),
      child: TransformerPageView(
          loop: false,
          key: _pageViewKey,
          index: _pageValueNotifier?.value ?? _getInitPositon(),
          transformer: new ScaleAndFadeTransformer(),
          pageController: _pageController,
          itemBuilder: (BuildContext context, int index) {
            return Center(
              child: _toItemWidget(
                  context, urlList?.elementAt(index % (urlList.length)), index),
            );
          },
          onPageChanged: (int index) async {
            await Future.delayed(Duration(milliseconds: 400), () {
              _pageValueNotifier?.value = index;
              if(!StringUtils.isEmpty(_selectId)){
                _selectId = urlList?.elementAt(index % (urlList?.length))?.id;
                urlList?.elementAt(index % (urlList?.length))?.editStopFlg = !StringUtils.isEmpty(_selectId)?"01":"02";
                widget?.onRepeat?.call(urlList?.elementAt(index % (urlList?.length)));
                setState(() {
                });
              }
            });

          },
          itemCount: (urlList.length) * LIMIT_LOOP_COUNT),
    );
  }

  Widget _toItemWidget(BuildContext context,
      TerminalDetailListItemBean itemBean, int index) {
    return ClickBackgroundWidget(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        widget?.onTap?.call(itemBean);
      },
      onLongPress: (detail) {
        return MenuDialogUtils.showMenuDialog(context: context,
            longPressDetails: detail,
            itemMap: _getMenuMap(context, itemBean));
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Container(
          width: _itemWidth,
          height: _itemHeight,
          decoration: BoxDecoration(color: Colors.black),
          child: Stack(
            fit: StackFit.expand,
            children: <Widget>[
              VgCacheNetWorkImage(
                itemBean?.getCoverUrl() ?? "",
                fit: BoxFit.contain,
                imageQualityType: ImageQualityType.middleDown,
              ),
              Align(
                alignment: Alignment.topLeft,
                child: _toRepeatWidget(!StringUtils.isEmpty(_selectId) && _pageValueNotifier?.value == index),
              ),
              Center(
                child: Offstage(
                    offstage: !(itemBean?.isVideo() ?? false),
                    child: Opacity(
                      opacity: 0.5,
                      child: Image.asset(
                        "images/video_play_ico.png",
                        width: 52,
                      ),
                    )),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _toRepeatWidget(bool show){
    double opacityLevel = 1.0;
    return (show)?
    StreamBuilder<double>(
      initialData: 0,
      stream: Stream.periodic(Duration(milliseconds: 500), (value){
        opacityLevel = opacityLevel == 0 ? 1.0 : 0.0;
        return opacityLevel;
      }),
      builder: (context, snapshot){
        return AnimatedOpacity(
          opacity: snapshot.data,
          duration: Duration(milliseconds: 500),
          curve: Curves.linear,
          child: Container(
            padding: const EdgeInsets.only(left: 7, top: 7),
            child: Image.asset(
              "images/icon_repeat.png",
              width: 20,
              height: 20,
            ),
          ),
        );
      },
    )
        :Container();
  }

  Map<String, ValueChanged> _getMenuMap(BuildContext context,
      TerminalDetailListItemBean itemBean) {
    return {
      "重命名": (_) {
        widget?.onUpdateName?.call(itemBean);
      },
      "取消播放": (_) {
        widget?.onDeleteTap?.call(itemBean);
      },
      "删除文件": (_) {
        widget?.onDeleteForever?.call(itemBean);
      }
    };
  }

  String _getFolderNameStr(int index) {
    if (index == null || index < 0) {
      index = 0;
    }
    if (urlList == null || urlList.isEmpty) {
      return null;
    }
    String folderName =
        urlList
            .elementAt(index % (urlList?.length ?? 1))
            ?.picname;
    if (StringUtils.isEmpty(folderName)) {
      return null;
    }
    return folderName;
  }
}

class ScaleAndFadeTransformer extends PageTransformer {
  final double _scale;
  final double _fade;

  ScaleAndFadeTransformer({double fade: 0.3, double scale: 0.8})
      : _fade = fade,
        _scale = scale;

  @override
  Widget transform(Widget item, TransformInfo info) {
    double position = info.position;
    double scaleFactor = (1 - position.abs()) * (1 - _scale);
    double fadeFactor = (1 - position.abs()) * (1 - _fade);
    double opacity = _fade + fadeFactor;
    double scale = _scale + scaleFactor;
    return new Opacity(
      opacity: opacity,
      child: new Transform.scale(
        scale: scale,
        child: item,
      ),
    );
  }
}
